<template>
    <div class="policyGroupManage">
        <div style="padding:10px;margin: 6px 10px;">
            <SearchComponent :searchConfig="policyGroupSearchConfig" @resetFn="reset" @searchFn="queryFn">
                <template #creator>
                    <el-select v-model="creator" :remote-method="remoteMethod" clearable filterable placeholder="创建人" remote
                        reserve-keyword style="width: 100%" @change="selectInputChange" @focus="focus('borrowNo')">
                        <el-option v-for="item in creatorOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </template>
            </SearchComponent>
        </div>

        <div class="content" style="bottom: 10px;">
            <div class="policyGroupContent">
                <div style="margin: 10px -10px;">
                    <el-button :disabled="!btnPermission['PolicyGroupManage-creatNewPolicy']" size="small" type="primary"
                        @click="creatNewPolicy">创建新策略组
                    </el-button>
                    <span style="margin: 0px 20px;color: rgb(64, 158, 255);"> <i class="el-icon-info"></i>
                        <span>提示：点击行即可展示组中策略</span>
                    </span>
                    <span style="margin: 0px 20px;color: rgb(64, 158, 255);"> <i class="el-icon-info"></i>
                        <span>提示：新配置的策略组会覆盖旧策略组的配置，可能存在未涉及车辆的策略组。</span>
                    </span>
                </div>
                <el-row style="padding: 13px 10px;background-color: #f4f4f5;margin: 0px -10px;">
                    <el-col :span="2">
                        策略组ID
                    </el-col>
                    <el-col :span="3">
                        策略组名
                    </el-col>
                    <el-col :span="4">
                        描述
                    </el-col>
                    <el-col :span="3">
                        创建人
                    </el-col>
                    <el-col :span="4">
                        创建时间
                    </el-col>
                    <el-col :span="4">
                        状态
                    </el-col>
                    <el-col :span="4">
                        操作
                    </el-col>
                </el-row>
                <div class="demo-collapse">
                    <el-collapse v-model="activeName" v-loading="groupLoading" accordion @change="handleChange">
                        <el-collapse-item v-for="item in groupPolicyList" :name="item.id">
                            <template #title>
                                <el-row style="display: contents;">
                                    <el-col :span="2">
                                        {{ item.id }}
                                    </el-col>
                                    <el-col :span="3">
                                        {{ item.groupName }}
                                    </el-col>
                                    <el-tooltip effect="dark"  placement="top-start" :content="item.description" >
                                        <el-col :span="4" class="text-overflow">
                                            {{ item.description }}
                                        </el-col>
                                    </el-tooltip>
                                    <el-col :span="3">
                                        {{ item.createBy }}
                                    </el-col>
                                    <el-col :span="4">
                                        {{ item.createTime }}
                                    </el-col>
                                    <el-col :span="4">
                                        <el-tag type="danger" v-if="item.status == 0">暂停</el-tag>
                                        <el-tag type="success" v-if="item.status == 1">启用</el-tag>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-button type="text"
                                            @click="carDialogTableVisible = true, showCars(item.id, $event)"
                                            size="small">涉及车辆</el-button>
                                        <el-button :disabled="!btnPermission['PolicyGroupManage-updateFn']" size="small"
                                            type="text" @click="updateFn(item, $event)">更新
                                        </el-button>
                                        <el-popconfirm title="确定要删除吗?" @confirm='deleteFn(item)'>
                                            <template #reference>
                                                <el-button :disabled="!btnPermission['PolicyGroupManage-deleteFn']"
                                                    size="small" style="color:#f00;" type="text">删除
                                                </el-button>
                                            </template>
                                        </el-popconfirm>
                                    </el-col>
                                </el-row>
                            </template>
                            <el-table v-loading="strategyLoading" :data="strategyList" element-loading-text="加载中...">
                                <el-table-column prop="id" label="TriggerID" width="100">
                                </el-table-column>
                                <el-table-column prop="demandDepartment" label="提出部门" width="100">
                                </el-table-column>
                                <el-table-column prop="developDepartment" label="开发部门">
                                </el-table-column>
                                <el-table-column prop="sceneName" label="场景">
                                </el-table-column>
                                <el-table-column prop="strategyName" label="策略名称" min-width="120">
                                </el-table-column>
                                <el-table-column prop="strategyDesc" label="策略描述" min-width="200">
                                </el-table-column>
                                <el-table-column prop="modifyTime" label="修改时间" min-width="160">
                                </el-table-column>
                                <el-table-column prop="modifyBy" label="修改人" min-width="160">
                                </el-table-column>
                                <el-table-column label="优先级" prop="priority" width="90">
                                    <template #default="{ row }">
                                        <span>{{ row.priority }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="状态" prop="status" width="80">
                                    <template #default="{ row }">
                                        <span v-if="row.status == 0">暂停</span>
                                        <span v-if="row.status == 1">启用</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="120">
                                    <!-- <el-button type="text" @click="stopPropagation">涉及车辆</el-button>
                                    <el-button :disabled="!btnPermission['PolicyGroupManage-updateFn']" size="small"
                                        type="text" @click="updateFn(item, $event)">更新
                                    </el-button> -->
                                </el-table-column>
                            </el-table>
                            <el-pagination :currentPage="strategyListPageData.current"
                                v-model:page-size="strategyListPageData.size" :total="strategyListPageData.total" background
                                layout="total, prev, pager, next" style="margin: 10px 0px;float: left"
                                @current-change="strategyListPageChange">
                            </el-pagination>
                        </el-collapse-item>
                    </el-collapse>
                </div>
                <el-pagination :currentPage="groupPolicyPageData.current" v-model:page-size="groupPolicyPageData.size"
                    :page-sizes="[10, 20, 30, 40, 50]" :total="groupPolicyPageData.total" background
                    layout="total, sizes, prev, pager, next, jumper" style="margin: 20px 10px;float: right"
                    @size-change="handleSizeChange" @current-change="groupPolicyPageChange">
                </el-pagination>
                <el-dialog v-model="carDialogTableVisible" title="涉及车辆" width="66%">
                    <div v-if="!strategyListPageData.hasConfig">无数据</div>
                    <div v-else>
                        <el-row>
                            <el-col :span="6" v-for="(item, index)  in   strategyConfigList  ">
                                <el-card style="margin: 5px 0px 5px 5px;cursor: pointer;" shadow="hover"
                                    :body-style="{ 'background-color': item.backgroundColor }"
                                    @click="queryCarsByStrategyConfig(item.id, index)">
                                    <div>
                                        <h3 style="margin: -5px 0px;">配置-{{ item.id }} &nbsp;&nbsp; <el-popover
                                                placement="top-start" trigger="hover" width="280">
                                                <template #reference>
                                                    <el-button class="m-2" type="text">详情</el-button>
                                                </template>
                                                <el-descriptions :column="1" :size="size" :style="blockMargin">
                                                    <el-descriptions-item label="采集秒数">前{{ item.collectTimeBefore
                                                    }}/后{{ item.collectTimeAfter }}</el-descriptions-item>
                                                    <el-descriptions-item label="最大触发">
                                                        <span v-if="item.cycle == 'day'">{{ item.triggerCount }}次/天</span>
                                                        <span v-if="item.cycle == 'month'">{{ item.triggerCount
                                                        }}次/月</span>
                                                    </el-descriptions-item>
                                                    <el-descriptions-item label="触发性能监控的故障等级">{{ item.plogFaultLevel
                                                    }}</el-descriptions-item>
                                                    <el-descriptions-item label="性能监控">
                                                        <span v-if="item.plogLongtermMonitor == 0">关闭</span>
                                                        <span v-if="item.plogLongtermMonitor == 1">开启</span>
                                                    </el-descriptions-item>
                                                    <el-descriptions-item label="全量日志上传">
                                                        <span v-if="item.uploadAllLog == 0">否</span>
                                                        <span v-if="item.uploadAllLog == 1">是</span>
                                                    </el-descriptions-item>
                                                </el-descriptions>
                                            </el-popover></h3>
                                        <div>申请人：{{ item.applicant }}</div>
                                        <div>{{ item.modifyTime }}</div>
                                    </div>
                                </el-card>
                            </el-col>
                        </el-row>
                        <div style="margin: 6px 0px;">
                            <el-radio-group v-model="allOrCurrent" @change="allOrCurrentChange()" size="small">
                                <el-radio-button label="当前生效" />
                                <el-radio-button label="历史配置" />
                            </el-radio-group>
                            <el-input placeholder="请输入车辆VIN" v-model="carVinSearch"
                                style="width: 200px;top: 2px;margin-left: 10px;" suffix-icon="el-icon-search" clearable
                                size="small">
                            </el-input>
                            <el-button type="primary" style="margin-left: 10px;top: 2px;" @click="searchCars()"
                                size="small">查询</el-button>
                            <el-pagination :currentPage="carPageData.current" v-model:page-size="carPageData.size"
                                :total="carPageData.total" background layout="total, prev, pager, next,"
                                style="margin:3px 0px;float: right" @current-change="carPageChange">
                            </el-pagination>
                        </div>
                        <el-table v-loading="carListLoading" :data="carList">
                            <el-table-column property="vin" label="VIN号" min-width="120" />
                            <el-table-column property="virtualVin" label="虚拟VIN号" min-width="260"></el-table-column>
                            <el-table-column label="智驾域控类型">
                                <template #default="scope">
                                    <span v-if="scope.row.domainControlType == 0">MDC</span>
                                    <span v-if="scope.row.domainControlType == 1">TDA4</span>
                                    <span v-if="scope.row.domainControlType == 2">J3</span>
                                    <span v-if="scope.row.domainControlType == 3">ADC</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="车辆用途类型">
                                <template #default="scope">
                                    <span v-if="scope.row.vehicleUseType == 0">量产车</span>
                                    <span v-if="scope.row.vehicleUseType == 1">研发车</span>
                                    <span v-if="scope.row.vehicleUseType == 2">台架</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-dialog>
            </div>
        </div>

        <PopComponent ref="popComponent" />

    </div>
</template>

<script>
import TableComponent from '@/components/TableComponent.vue';
import PopComponent from './components/PopComponent.vue';
import { groupPolicyListApi, policyGroupDeleteApi, getStrategyPageByStrategyGroupIdApi, getRelationCarPageByStrategyConfigIdApi, getCurrentCarPageByStrategyConfigIdApi, getStrategyConfigListByGroupIdApi } from '@/api/carManage/policyManage.js';
import { policyGroupSearchConfig, policyGroupTableColumns, tableColumns } from '@/constant/config.js';
import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import SearchComponent from '@/components/SearchComponent.vue';
import { useStore } from 'vuex';
import { getAllUserData } from "@/api/asset";
import { isEmpty } from "@/utils/util.js";

export default {
    components: {
        TableComponent,
        PopComponent,
        SearchComponent,
    },
    setup() {
        const strategyListPageData = reactive({
            total: 0,
            current: 1,
            size: 10,
            tmpId: 0,
            hasConfig: true
        });
        const carVinSearch = ref('')
        const activeName = ref('1')
        const handleChange = (id) => {
            if (!isEmpty(activeName.value)) {
                strategyListPageData.current = 1
                strategyListPageData.tmpId = id
                getStrategyList()
            }
        }
        const getStrategyList = () => {
            strategyLoading.value = true
            getStrategyPageByStrategyGroupIdApi({
                size: 10,
                current: strategyListPageData.current,
                groupId: strategyListPageData.tmpId
            }).then((res) => {
                if (res.data.code === 200) {
                    let response = res.data.data;
                    strategyList.value = response.records;
                    strategyListPageData.total = response.total;
                    strategyListPageData.current = response.current;
                }
                strategyLoading.value = false
            });
        }
        const showCars = (groupId, e) => {
            e.stopPropagation()
            carList.value = []
            strategyListPageData.hasConfig = true
            allOrCurrent.value = '当前生效'
            getStrategyConfigListByGroupIdApi({
                size: 10,
                current: strategyListPageData.current,
                groupId: groupId
            }).then((res) => {
                if (res.data.code === 200) {
                    let response = res.data.data;
                    strategyConfigList.value = response.records;
                    if (strategyConfigList.value.length != 0) {
                        strategyConfigList.value.forEach((item, index) => {
                            if (0 === index) {
                                item.backgroundColor = "#5f61e833"
                                carPageData.strategyConfigId = item.id
                                getCarList()
                            }
                        })
                    } else {
                        strategyListPageData.hasConfig = false
                    }
                }
                strategyLoading.value = false
            });

        }
        const groupPolicyPageData = reactive({
            total: 0,
            current: 1,
            size: 10,
        });
        const carPageData = reactive({
            total: 0,
            current: 1,
            size: 10,
            strategyConfigId: ''
        });
        const creator = ref();
        const allOrCurrent = ref('当前生效');
        const groupLoading = ref(false);
        const strategyLoading = ref(false);
        const carDialogTableVisible = ref(false);
        const strategyConfigList = ref([]);
        const strategyList = ref([]);
        const carList = ref([]);
        const popComponent = ref(null);
        const tmpItem = ref(null);
        const filterObj = ref({});

        const queryFn = (para) => {
            filterObj.value = para;
            groupPolicyPageData.current = 1;
            filterObj.value = {
                ...para,
                creator: creator.value
            };


            getGroupPolicyList();
        };

        const reset = () => {
            filterObj.value = {};
            groupPolicyPageData.current = 1;
            filterQuery.orderByType = '';
            creator.value = '';
            getGroupPolicyList();
        };
        const store = useStore();
        const btnPermission = computed(() => store.state.btnPermission);
        const groupPolicyList = ref([]);

        const selectInputChange = (val) => {

        }
        const getGroupPolicyList = (size = 10) => {
            groupPolicyListApi({
                size: size,
                current: groupPolicyPageData.current,
                ...filterObj.value,
                ...filterQuery,
            }).then((res) => {
                if (res.data.code === 200) {
                    let response = res.data.data;
                    groupPolicyList.value = response.records;
                    groupPolicyPageData.total = response.total;
                    groupPolicyPageData.current = response.current;
                }
            });
        };
        const handleSizeChange = (number) => {
            groupPolicyPageData.size = number;
            getGroupPolicyList(number)
        }
        const router = useRouter();
        const creatNewPolicy = () => {
            router.push({
                path: '/triggerConfiguration/CreateGroupPolicy',
            });
        };
        const updateFn = (item, e) => {
            e.stopPropagation()
            sessionStorage.setItem('policyGroupRowData', JSON.stringify(item));

            router.push({
                path: '/triggerConfiguration/UpdateGroupPolicy',
                // params:{
                //     id:123213
                // }
                // query: {
                //     id: row.id,
                // }
            });
        };
        const deleteFn = (row) => {
            let userNo;
            try {
                userNo = JSON.parse(localStorage.getItem('userInfo')).employeeId;
            } catch (e) {
            }

            policyGroupDeleteApi({
                userNo: userNo,
                id: row.id,
            }).then((res) => {
                if (res.data.code === 200) {
                    ElMessage({
                        message: '删除成功',
                        type: 'success',
                    });
                    getGroupPolicyList();
                } else {
                    ElMessage({
                        message: '删除失败',
                        type: 'error',
                    });
                }
            });
        };
        const creatorOptions = ref([])
        const remoteMethod = (query, userId, id) => {
            creatorOptions.value = [];
            if (query !== '' || id != '') {
                getAllUserData({
                    username: query,
                    employeeId: id
                }).then((res) => {
                    if (res.data.code == 200) {

                        if (res.data.data.records.length > 0) {
                            res.data.data.records.forEach((item, index) => {
                                creatorOptions.value.push({
                                    value: item.employeeId,
                                    label: item.username + '/' + item.employeeId
                                })
                            })
                        } else {
                            creatorOptions.value = [{
                                value: query,
                                label: query
                            }]
                        }

                    }
                })
            } else {
                creatorOptions.value = [];
            }
        }
        const focus = (focus) => {
        }
        onMounted(() => {
            getGroupPolicyList();
        });
        const filterQuery = reactive({});

        const groupPolicyPageChange = (val) => {
            groupPolicyPageData.current = val;
            getGroupPolicyList(groupPolicyPageData.size);
        };


        const strategyListPageChange = (val) => {
            strategyListPageData.current = val;
            getStrategyList();
        };

        const queryCarsByStrategyConfig = (strategyConfigId, strategyConfigIndex) => {
            strategyConfigList.value.forEach((item, index) => {
                if (strategyConfigIndex === index) {
                    item.backgroundColor = "#5f61e833"
                } else {
                    item.backgroundColor = ""
                }
            })
            carPageData.strategyConfigId = strategyConfigId
            getCarList()
        };

        const carPageChange = (val) => {
            carPageData.current = val;
            getCarList();
        };

        const getCarList = () => {
            carList.value = []
            if (allOrCurrent.value === '当前生效') {
                getCurrentCarPageByStrategyConfigIdApi({
                    size: 10,
                    current: carPageData.current,
                    configId: carPageData.strategyConfigId,
                    vin: carVinSearch.value
                }).then((res) => {
                    if (res.data.code === 200) {
                        let response = res.data.data;
                        carList.value = response.records;
                        carPageData.total = response.total;
                        carPageData.current = response.current;
                    }
                    strategyLoading.value = false
                });
            }

            if (allOrCurrent.value === '历史配置') {
                getRelationCarPageByStrategyConfigIdApi({
                    size: 10,
                    current: carPageData.current,
                    configId: carPageData.strategyConfigId,
                    vin: carVinSearch.value
                }).then((res) => {
                    if (res.data.code === 200) {
                        let response = res.data.data;
                        carList.value = response.records;
                        carPageData.total = response.total;
                        carPageData.current = response.current;
                    }
                    strategyLoading.value = false
                });
            }
        }

        const allOrCurrentChange = () => {
            carPageData.total = 0;
            carPageData.current = 1;
            getCarList()
        }

        const searchCars = () => {
            carPageData.total = 0;
            carPageData.current = 1;
            getCarList()
        }

        return {
            tableColumns,
            policyGroupTableColumns,
            strategyList,
            groupLoading,
            strategyLoading,
            updateFn,
            tmpItem,
            deleteFn,
            popComponent,
            creatNewPolicy,
            groupPolicyPageData,
            strategyListPageData,
            groupPolicyPageChange,
            strategyListPageChange,
            groupPolicyList,
            getGroupPolicyList,
            policyGroupSearchConfig,
            queryFn,
            reset,
            filterObj,
            filterQuery,
            btnPermission,
            handleSizeChange,
            remoteMethod,
            focus,
            creatorOptions,
            creator,
            activeName,
            handleChange,
            showCars,
            carDialogTableVisible,
            strategyConfigList,
            queryCarsByStrategyConfig,
            carPageData,
            carList,
            carPageChange,
            allOrCurrent,
            allOrCurrentChange,
            carVinSearch,
            searchCars
        };
    },
};
</script>


<style lang="less" scoped>
.policyGroupManage {
    //background: #eeeeee;
    min-height: 100%;

    .content {
        padding: 0px 10px;
        margin: -26px 10px;

        .policyGroupContent {
            background: #ffffff;
            padding: 0px 10px;
        }
    }

    /deep/.el-dialog__body {
        padding: 0px 20px;
    }
    .text-overflow{
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
</style>
